package com.hourse.platform.service.impl;

import com.hourse.platform.common.ErrorMsg;
import com.hourse.platform.entity.MenuButtonEntity;
import com.hourse.platform.entity.MenuEntity;
import com.hourse.platform.entity.RoleGroupEntity;
import com.hourse.platform.exception.AppException;
import com.hourse.platform.service.MenuService;
import com.hourse.platform.service.RoleService;
import com.hourse.platform.utils.BeanTools;
import com.hourse.platform.utils.SqlParams;
import com.hourse.platform.utils.StringTools;
import com.hourse.platform.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends PublicServiceImpl implements RoleService {

  @Autowired
  private MenuService menuService;

  /**
   * @功能描述: 【获取角色数据】
   */
  @Transactional(readOnly = true)
  @Override
  public List<RoleVO> getRoleList() {
    SqlParams sqlParams = new SqlParams()
      .append(" select new com.hourse.platform.vo.RoleVO(a.id,a.name,a.code)")
      .append(" from RoleEntity a");
    return baseDao.getItemListByNativeHQL(sqlParams.getSql(),null);
  }

  @Transactional(readOnly = true)
  @Override
  public Map<String, String> getRoleMap() {
    SqlParams sqlParams = new SqlParams()
            .append(" from RoleGroupEntity a");
    List<RoleGroupEntity> list =  baseDao.getItemListByNativeHQL(sqlParams.getSql(),null);

    Map<String, String> map = new HashMap<>();
    for (RoleGroupEntity roleGroupEntity : list) {
      map.put(roleGroupEntity.getId(),roleGroupEntity.getCode());
    }

    return map;
  }

  /**
   * @功能描述: 【获取角色菜单】
   * @param roleId
   */
  @Transactional(readOnly = true)
  @Override
  public List<RoleMenuVO> getRoleMenuList(String roleId) {

    SqlParams sqlParams = new SqlParams()
      .append(" select new com.hourse.platform.vo.RoleMenuVO(a.id,a.roleId,a.menuId,b.name)")
      .append(" from RoleMenuEntity a left join MenuEntity b on a.menuId = b.id ")
      .append(" where a.roleId = :roleId")
      .add("roleId",roleId);

    return baseDao.getItemListByNativeHQL(sqlParams.getSql(),sqlParams.getParams());
  }

  /**String id, String roleId, String menuId, String menuButtonId, String buttonName, String buttonUrl
   * @功能描述: 【获取角色菜单按钮权限列表】
   * @param roleId
   * @param menuId
   */
  @Transactional(readOnly = true)
  @Override
  public List<RoleMenuButtonVO> getRoleMenuButtonList(String roleId, String menuId) {

    SqlParams sqlParams = new SqlParams()
      .append(" select ")
      .append(" new com.hourse.platform.vo.RoleMenuButtonVO(a.id,a.roleId,a.menuId,a.menuButtonId,b.buttonName,b.url)")
      .append(" from RoleMenuButtonEntity a ")
      .append(" left join MenuButtonEntity b on a.menuButtonId = b.id")
      .append(" where a.roleId = :roleId")
      .append(" and a.menuId = :menuId")
      .add("roleId",roleId)
      .add("menuId",menuId);

     return baseDao.getItemListByNativeHQL(sqlParams.getSql(),sqlParams.getParams());
  }

  /**
   * 获取角色权限菜单
   *
   * @param menuId
   * @param roleId
   * @return
   */
  @Transactional(readOnly = true)
  @Override
  public List<MenuVO> getMenuList(String menuId, String roleId) {
    SqlParams sqlParams = new SqlParams()
      .append("from MenuEntity a where 1 = 1 ");

    if(StringTools.isNotNull(menuId)){
      sqlParams.append(" and a.parentId = :parentId");
      sqlParams.add("parentId",menuId);
    } else {
      sqlParams.append(" and a.parentId is null");
    }
    sqlParams.append(" order by a.sort");

    List<MenuEntity> tempData = baseDao.getItemListByNativeHQL(sqlParams.getSql(),sqlParams.getParams());

    List<MenuVO> listData = new ArrayList();

    for(MenuEntity data : tempData){
      MenuVO mvo = (MenuVO)BeanTools.BindEnityUnValidate(data,MenuVO.class);
      mvo.setHasChildren(data.getChildren().size() > 0 ? "true" : "");
      mvo.setAuth(isAuth(roleId,mvo.getId()) ? "1" : "0");
      listData.add(mvo);
    }

    return listData;
  }

  /**
   * @功能描述: 【删除角色菜单】
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void deleteRoleMenu(RoleMenuVO roleMenuVO) throws Exception {

    SqlParams sqlParams = SqlParams.New().append("delete from role_menu where role_id = :roleId")
      .append(" and menu_id = :menuId")
      .add("roleId",roleMenuVO.getRoleId()).add("menuId",roleMenuVO.getMenuId());


    baseDao.executeSqlUpdate(sqlParams.getSql(),sqlParams.getParams());
  }

  /**
   * @功能描述: 【后去角色菜单按钮权限】
   */
  @Transactional(readOnly = true)
  @Override
  public List<MenuButtonVO> getMenuButtonList(String menuId, String roleId) throws AppException {

    List<MenuButtonEntity> list = menuService.getMenuButtonList(menuId);
    List<MenuButtonVO> buttonList = new ArrayList<>();

    for(MenuButtonEntity button : list){
      MenuButtonVO menuButton = null;
      try {
        menuButton = (MenuButtonVO)BeanTools.BindEnity(button,MenuButtonVO.class);
      }catch (Exception e){
        throw ErrorMsg.SYSTEM_ERR.Exception();
      }
      menuButton.setAuth(isButtonAuth(button.getId(),roleId,menuId) ? "1" : "0");

      buttonList.add(menuButton);
    }

    return buttonList;
  }

  /**
   * @param roleMenuButtonVO
   * @功能描述: 【删除角色权限按钮】
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void deleteRoleMenuButton(RoleMenuButtonVO roleMenuButtonVO)  throws Exception {
    SqlParams sqlParams = SqlParams.New().append("delete from role_menu_button where role_id = :roleId")
      .append(" and menu_id = :menuId and menu_button_id =:buttonId")
      .add("roleId",roleMenuButtonVO.getRoleId()).add("menuId",roleMenuButtonVO.getMenuId())
      .add("buttonId",roleMenuButtonVO.getMenuButtonId());


    baseDao.executeSqlUpdate(sqlParams.getSql(),sqlParams.getParams());
  }

  /**
   * @功能描述: 【获取系统角色组列表】
   */
  @Transactional(readOnly = true)
  @Override
  public List<RoleVO> getRoleGroupList() {

    SqlParams sqlParams = new SqlParams()
      .append(" select new com.hourse.platform.vo.RoleVO(a.id,a.name,a.code)")
      .append(" from RoleGroupEntity a");
    return baseDao.getItemListByNativeHQL(sqlParams.getSql(),null);
  }

  /**
   * @功能描述: 【获取角色组ITEML】
   */
  @Transactional(readOnly = true)
  @Override
  public List<RoleGroupItemVO> roleGroupItemList(String roleGroupId) {

    SqlParams sqlParams = new SqlParams()
      .append(" select new com.hourse.platform.vo.RoleGroupItemVO(")
      .append(" a.id,b.name,b.code,b.id")
      .append(" ) from RoleGroupItemEntity a ")
      .append(" left join RoleEntity b on a.roleId = b.id")
      .append(" where a.roleGroupId = :roleGroupId");

    sqlParams.add("roleGroupId",roleGroupId);

    return baseDao.getItemListByNativeHQL(sqlParams.getSql(),sqlParams.getParams());
  }

  /**
   * QD 渠道
   * FGS  分公司
   * XTGLY 系统管理员
   * @param code
   * @return
   */
  @Transactional
  @Override
  public String getRoleIdByCode(String code) {
    SqlParams sqlParams = new SqlParams();
    sqlParams.append("select a.id from RoleGroupEntity a")
            .append(" where a.code = :code");

    sqlParams.add("code",code);

    return (String) baseDao.execSingleQuery(sqlParams.getSql(),sqlParams.getParams());
  }

  @Transactional
  @Override
  public String getRoleGroupIdByName(String name) {

    SqlParams sqlParams = new SqlParams()
            .append(" select a.id from RoleGroupEntity a ")
            .append(" where a.name = :name");
    sqlParams.add("name",name);

    return (String) baseDao.execSingleQuery(sqlParams.getSql(),sqlParams.getParams());
  }

  @Transactional
  @Override
  public Map<String, RoleGroupEntity> getRoleGroupEntityMap() {

    SqlParams sqlParams = new SqlParams()
            .append(" from RoleGroupEntity a");
    List<RoleGroupEntity> list =  baseDao.getItemListByNativeHQL(sqlParams.getSql(),null);

    Map<String, RoleGroupEntity> map = new HashMap<>();
    for (RoleGroupEntity roleGroupEntity : list) {
      map.put(roleGroupEntity.getId(),roleGroupEntity);
    }

    return map;
  }

  @Transactional(readOnly = true)
  public List<RoleGroupEntity> getRoles(String userId){
    SqlParams sqlParams = new SqlParams();
    sqlParams.append("from RoleGroupEntity where id in (");
    sqlParams.append("select roleId from UserRoleEntity where userId = :userId)");
    sqlParams.add("userId",userId);
    List<RoleGroupEntity> list =  baseDao.getItemListByNativeHQL(sqlParams.getSql(),sqlParams.getParams());

    return list;
  }

  /**
   * 判断该角色是否有权限该菜单按钮权限
   * @param roleId
   * @param menuId
   * @return
   */
  @Transactional(readOnly = true)
  boolean isButtonAuth(String buttonId,String roleId, String menuId){

    SqlParams sqlParams = new SqlParams()
      .append("from RoleMenuButtonEntity a where a.roleId = :roleId and a.menuId = :menuId ")
      .append(" and a.menuButtonId =:menuButtonId")
      .add("roleId",roleId)
      .add("menuButtonId",buttonId)
      .add("menuId",menuId);

    List list =  baseDao.getItemListByNativeHQL(sqlParams.getSql(),sqlParams.getParams());

    return list.size() > 0;
  }

  /**
   * 判断是否有权限
   * @param roleId
   * @param menuId
   * @return
   */
  @Transactional(readOnly = true)
  boolean isAuth(String roleId, String menuId){

    SqlParams sqlParams = new SqlParams()
      .append("from RoleMenuEntity a where a.roleId = :roleId and a.menuId = :menuId ")
      .add("roleId",roleId)
      .add("menuId",menuId);

   List list =  baseDao.getItemListByNativeHQL(sqlParams.getSql(),sqlParams.getParams());

   return list.size() > 0;
  }



}
